package com.youlai.system.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.system.converter.MyRoleConverter;
import com.youlai.system.mapper.RoleMapper;
import com.youlai.system.model.entity.Role;
import com.youlai.system.model.form.MyRoleForm;
import com.youlai.system.model.query.RoleQuery;
import com.youlai.system.model.vo.RoleVO;
import com.youlai.system.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    private final MyRoleConverter roleConverter;
    private final RoleMapper roleMapper;

    @Override
    public Page<RoleVO> getRoelPage(RoleQuery queryParams) {
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();

        Page<Role> rolePage = this.page(
                new Page<>(pageNum, pageSize),
                new LambdaQueryWrapper<Role>()
                        .select(Role::getId, Role::getName, Role::getDescription, Role::getState)
        );
        Page<RoleVO> page = roleConverter.entityPage(rolePage);
        return page;

    }

    @Override
    public Integer saveRole(MyRoleForm formData) {
        Role entity = roleConverter.formEntity(formData);

        boolean result = this.saveOrUpdate(entity);
        Assert.isTrue(result,"部门保存失败");
        return entity.getId();
    }

    @Override
    public boolean deleteByIds(String ids) {
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<Role>()
                .eq("id",ids);
        return this.remove(roleQueryWrapper);
    }

    @Override
    public MyRoleForm getRoleForm(Long id) {
        Role entity = this.getById(id);
        String RolePer = entity.getPermIds();
        MyRoleForm roleForm = roleConverter.entityForm(entity);
        roleForm.setPermIdsArr(RolePer.split(","));
        return roleForm;
    }

    @Override
    public List getLIstRole() {
        return roleMapper.getRoleList();
    }

    @Override
    public Integer insertPermIds(Integer id,String permIds) {
        return roleMapper.insertPer(id,permIds);
    }


}
